/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaz;

import ecu911.ClaseServicios;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.Timer;

/**
 *
 * @author User
 */
public class LoginUsuario extends javax.swing.JDialog {

    private Frame pasoElFramePrincipal; //Para cerrar la ventana principal
    ClaseServicios usuarioSistema = new ClaseServicios();
    public static ArrayList usuarioActivo = new ArrayList();
    public Timer objetotimer;
    public int a;
    /**
     * Creates new form LoginUsuario
     */
    public LoginUsuario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.getContentPane().setBackground(Color.white);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); 
        pasoElFramePrincipal = parent;
        this.btnCancelar.setBackground(Color.white);
        this.btnIngresar.setBackground(Color.white);
        this.soloNumeros(txtUsuario);
        this.barra.setForeground(Color.lightGray);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        btnIngresar = new javax.swing.JButton();
        txtPassword = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        btnCancelar = new javax.swing.JButton();
        barra = new javax.swing.JProgressBar();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Fondo911Principal.jpg"))); // NOI18N

        jPanel1.setBackground(new java.awt.Color(255, 102, 0));

        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Usuario:");

        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Password:");

        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyPressed(evt);
            }
        });

        btnIngresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/16 (Exit).gif"))); // NOI18N
        btnIngresar.setText("Ingresar");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)
                    .addComponent(txtPassword))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnIngresar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(btnIngresar)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel4.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(0, 0, 102));
        jLabel4.setText("Registrar nuevo usuario.");
        jLabel4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabel4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel4MouseClicked(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/cancelar.gif"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(72, 72, 72)
                        .addComponent(btnCancelar))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(barra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(45, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(btnCancelar))
                .addGap(18, 18, 18)
                .addComponent(barra, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-381)/2, (screenSize.height-393)/2, 381, 393);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        int ope = JOptionPane.showConfirmDialog(null, "¿Cerrar Sistema Llamadas911?",
                  "EXIT",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE,null);
        if (ope == 0){
            this.dispose();
            //pasoElFramePrincipal.dispose();
            
        }
    }//GEN-LAST:event_formWindowClosing

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        int ope = JOptionPane.showConfirmDialog(null, "¿Cerrar Sistema Llamadas911?",
                  "EXIT",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE,null);
        if (ope == 0){
            this.dispose();
            //pasoElFramePrincipal.dispose();
            
        }
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
      
    }//GEN-LAST:event_formWindowClosed

     private boolean informacionCompleta(){
        boolean resultado = false;
        String password = new String(txtPassword.getPassword());
        if(!password.equals("") && !txtUsuario.getText().equals("")){
            resultado = true;
        }
        return resultado;
    }
    
    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
        // TODO add your handling code here:
         if(this.validarCamposTextoCompleto()){
            String password = new String(txtPassword.getPassword());
            usuarioActivo = usuarioSistema.conectarUsuario(txtUsuario.getText(), password);
            objetotimer = new Timer(80,new claseTimer());
            try
	    {
                if(!usuarioActivo.isEmpty()){
                    JOptionPane.showConfirmDialog(null,"Bienvenido " + usuarioActivo.get(1) + " " + usuarioActivo.get(2),
                    "Sistema Iniciado",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
                    objetotimer.start();
                    
                }
                else{
                    JOptionPane.showConfirmDialog(null,"Usuario no existe o los datos son incorrectos.",
                    "Error",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
                }
            }
            catch (Exception e)
	    {
                e.printStackTrace();
	    }
        }
        else{
            JOptionPane.showConfirmDialog(null,"Información incompleta, llene todos los campos.",
            "Error",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
            this.pintarTextosVacios();
        }
    }//GEN-LAST:event_btnIngresarActionPerformed

    private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked
        // TODO add your handling code here:
        CrearUsuario ventanaNuevoUsuario = new CrearUsuario(pasoElFramePrincipal, true);
        ventanaNuevoUsuario.setVisible(true);
    }//GEN-LAST:event_jLabel4MouseClicked

    private void txtUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyPressed
        // TODO add your handling code here:
           
    }//GEN-LAST:event_txtUsuarioKeyPressed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10){
            if(this.validarCamposTextoCompleto()){
            String password = new String(txtPassword.getPassword());
            usuarioActivo = usuarioSistema.conectarUsuario(txtUsuario.getText(), password);
            objetotimer = new Timer(80,new claseTimer());
            try
	    {
                if(!usuarioActivo.isEmpty()){
                    JOptionPane.showConfirmDialog(null,"Bienvenido " + usuarioActivo.get(1) + " " + usuarioActivo.get(2),
                    "Sistema Iniciado",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
                    objetotimer.start();
                }
                else{
                    JOptionPane.showConfirmDialog(null,"Usuario no existe o los datos son incorrectos.",
                    "Error",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
                }
                }
            catch (Exception e)
	    {
                e.printStackTrace();
	    }
        }
        else{
                JOptionPane.showConfirmDialog(null,"Información incompleta, llene todos los campos.",
                "Error",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
                this.pintarTextosVacios();
            }
        }
    }//GEN-LAST:event_txtPasswordKeyPressed

    private void soloNumeros(JTextField a){
        a.addKeyListener(new KeyAdapter(){
            public void keyTyped(KeyEvent e){
                char c = e.getKeyChar();
                if(Character.isLetter(c)){
                    getToolkit().beep();
                    e.consume();
                }
            }
        }
                );
        
    }
    
    private boolean validarCamposTextoCompleto(){
       boolean check = true;
       if(this.txtUsuario.getText().compareTo("")==0 ||
          this.txtPassword.getPassword().length==0){
           check = false;
       }
       return check;
   }
    
    private void pintarTextosVacios(){
       if(this.txtUsuario.getText().compareTo("")==0){
           this.txtUsuario.setBackground(Color.yellow);
       }
       else{
           this.txtUsuario.setBackground(Color.white);
       }
       if(this.txtPassword.getPassword().length==0){
           this.txtPassword.setBackground(Color.yellow);
       }
       else{
           this.txtPassword.setBackground(Color.white);
       }
    }
    
    
    public class claseTimer implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
          a=barra.getValue();
          if (a<100){
              a+=2;
              barra.setValue(a);
               }
          else{
              objetotimer.stop();
              Menu menu = new Menu();
              menu.setVisible(true);
              cerrar();   
          }                  
          
        }
    
}
    
    
    private void cerrar(){
        this.dispose();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                LoginUsuario dialog = new LoginUsuario(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar barra;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
